﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using zqdn.Models.Auth;
using zqdn.Models.Ex;
using zqdn.Services.Auth;
using zqdn.Services.Interfaces.Case;
using zqdn.Services.Interfaces.Ex;
using zqdn.Web.App_Start;
using zqdn.Web.ViewModels;

namespace zqdn.Web.Controllers
{
    public class ExController : Controller
    {
        private readonly IExService _iexrepository;
        private readonly IGoodService _igoodrepository;
        private readonly IUserService _userService; 
        public ExController(IUserService userService, IExService iexrepository, IGoodService igoodrepository)
        {
            this._iexrepository = iexrepository;
            this._igoodrepository = igoodrepository;
            this._userService = userService;
        }

        public JsonResult List()
        {
            try
            {
                //if (SessionContext.CurrentUser == null)
                //{
                //    return Json(new { Result = "100002", msg = "尚未注册，请先注册" }, JsonRequestBehavior.AllowGet);
                //}
                var exlist = _iexrepository.getAllEx();
                var _result = Json(exlist, JsonRequestBehavior.AllowGet);
                return _result;
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = "服务异常" });
            }

        }

        public JsonResult Detail(int id)
        {
            try
            {
                //if (SessionContext.CurrentUser == null)
                //{
                //    return Json(new { Result = "100002", msg = "尚未注册，请先注册" }, JsonRequestBehavior.AllowGet);
                //}
                var ex = _iexrepository.getExByID(id);
                var _result = Json(ex, JsonRequestBehavior.AllowGet);
                return _result;
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = "服务异常" });
            }

        }

        public JsonResult GoodList()
        {
            try
            {
                //if (SessionContext.CurrentUser == null)
                //{
                //    return Json(new { Result = "100002", msg = "尚未注册，请先注册" }, JsonRequestBehavior.AllowGet);
                //}
                var goodlist = _igoodrepository.getAllGood();
                var _result = Json(goodlist, JsonRequestBehavior.AllowGet);
                return _result;
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = ex.ToString() }, JsonRequestBehavior.AllowGet);
            }

        }

        [HttpPost]
        public JsonResult AddChangeLog(ChangeViewModel model)
        {
            try
            {
                //if (SessionContext.CurrentUser == null)
                //{
                //    return Json(new { Result = "100002", msg = "尚未注册，请先注册" }, JsonRequestBehavior.AllowGet);
                //}
                //积分余额判断
                var re = _userService.GetUserByOprnID(model.OpenID);
                if (re.Integral < int.Parse(model.RequireJF))
                {
                    return Json(new { Result = "error", msg = "兑换失败,积分不足" });
                }
                ChangeLog clog = new ChangeLog
                {
                    GID = model.GID,
                    Address = model.Address,
                    UID = re.ID,
                    Name = model.Name,
                    Mobile = model.Mobile,
                    IsDeleted = false
                };
                _iexrepository.AddExChange(clog);
                re.Integral = re.Integral - int.Parse(model.RequireJF);
                _userService.UpdateUser(re);
                return Json(new { Result = "success", msg = "兑换成功", userInfo = re });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = "兑换失败" });
            }

        }

        [HttpPost]
        public JsonResult AddExLog(ExViewModel model)
        {
            // 1: 阅读学术资讯 2：最强比拼答题 3：上传病例审核通过 4：搜索病例
            try
            {
                var re = _userService.GetUserByOprnID(model.openID);
                var log = _iexrepository.getLogByType(model.Type, re.ID);
                var anlog = _iexrepository.getLogByEid(model.EID,re.ID); 
                ExLogs elog = new ExLogs();
                elog.UID = re.ID;
                if (model.Type != 4)
                {
                   elog.EID = model.EID; //积分类型ID
                }
                switch(model.Type) {
                    case 1 :
                        if (log == null) {
                            re.Integral = re.Integral + 2;
                            elog.Type = model.Type;
                            _iexrepository.AddExLog(elog);
                            _userService.UpdateUser(re);
                        }
                        break;
                    case 2 :
                        elog.Answer = model.Answer;
                        elog.isTrue = model.isTrue;
                        elog.Type = model.Type;
                        _iexrepository.AddExLog(elog);
                        if (anlog == null) {
                            re.Integral = re.Integral + 2;
                            _userService.UpdateUser(re);
                        }
                        break;
                    case 3 :
                            re.Integral = re.Integral + 20; //病例上传审核成功
                            elog.Type = model.Type;
                            _iexrepository.AddExLog(elog);
                            _userService.UpdateUser(re);
                        break;
                    case 4 :
                        if (log == null) {
                            re.Integral = re.Integral + 2;
                            elog.Type = model.Type;
                            _iexrepository.AddExLog(elog);
                            _userService.UpdateUser(re);
                        }
                        break;
                    case 5:
                        if (re.Integral >= 20)
                        {
                            re.Integral = re.Integral - 20; //取消病例审核
                        }
                        elog.Type = model.Type;
                        _iexrepository.AddExLog(elog);
                        _userService.UpdateUser(re);
                        break;
                    default:
                        break;

                }
              
                return Json(new { Result = "success", msg = "记录成功", userInfo = re });

            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = ex.ToString() });
            }

        }

        [HttpPost]
        public JsonResult GetAddressInfo(string openID)
        {
            try
            {
                var user = _userService.GetUserByOprnID(openID);
                var changeLog = _iexrepository.GetChangeLogsByUID(user.ID).OrderByDescending(o => o.CreatedTime).FirstOrDefault() ?? new ChangeLog();
                return Json(new { Result = "success", name = changeLog.Name, mobile = changeLog.Mobile, address = changeLog.Address });
            }
            catch (Exception e)
            {
                return Json(new { Result = "success", name = "", mobile = "", address = "" });
            }
        }

        [HttpGet]
        public JsonResult GetTodayUserExLogTimes(string openID)
        {
            int count = 0;
            if (!string.IsNullOrEmpty(openID))
            {
                var re = _userService.GetUserByOprnID(openID);
                var firstEx = _iexrepository.getAllEx().OrderBy(o => o.ID).FirstOrDefault();
                var log = _iexrepository.getLogsByType(2, re.ID).Where(o => o.EID == firstEx.ID).ToList();
                count = log.Count();
                return Json(new { Result = "success", msg = "读取记录成功", todayCount = count }, JsonRequestBehavior.AllowGet);
            }
            else {
                return Json(new { Result = "error", msg = "读取失败", todayCount = count }, JsonRequestBehavior.AllowGet);
            }
            
        }
    }
}